package edu.cicese.alz.swing.tables;

import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
import java.awt.Component;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 29/05/12
 * Time: 02:07 PM
 */
public class IntegerTableEditor extends AbstractCellEditor implements TableCellEditor {
	JTextField jTextField;

	public IntegerTableEditor() {
		jTextField = new JTextField();
	}

	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) {
		String s = String.valueOf(value);
		if (!s.equals("null")) {
			jTextField.setText(String.valueOf(value));
		}
		else {
			jTextField.setText("");
		}
		return jTextField;
	}

	public Object getCellEditorValue() {
		return jTextField.getText();
//		return null;
//		String s = jTextField.getText();
//		if (!s.equals("")) {
//			try {
//				int i = Integer.parseInt(s);
//			} catch (NumberFormatException nfe) {
//				System.out.println("Wrong entry: " + nfe.getMessage());
//				JOptionPane.showMessageDialog(null, "Data Input Error, Please enter Integer value", "Error", JOptionPane.ERROR_MESSAGE);
//				return Integer.valueOf(0);
//			}
//		} else {
//			JOptionPane.showMessageDialog(null, "Data Input Error, Plz Inter Integer value", "Error", JOptionPane.ERROR_MESSAGE);
//			return Integer.valueOf(0);
//		}
//		return Integer.valueOf(s);
	}

	public boolean stopCellEditing() {
		String s = jTextField.getText();
		if (!s.equals("")) {
			try {
				Integer.parseInt(s);
			} catch (NumberFormatException nfe) {
//				System.out.println("Wrong entry: " + nfe.getMessage());
//				JOptionPane.showMessageDialog(null, "Please enter an Integer value", "Data Input Error", JOptionPane.ERROR_MESSAGE);
				return false;
			}
		}
		return super.stopCellEditing();
	}
}